package vn.vfriends.id.bean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.context.RequestContext;
import org.primefaces.model.DualListModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.id.jpa.controller.PageJpaController;
import vn.vfriends.id.jpa.controller.RoleJpaController;
import vn.vfriends.id.jpa.entity.Page;
import vn.vfriends.id.jpa.entity.Role;

/**
 *
 * @author tuan@vfriends.vn
 */
@Named
@ConversationScoped
public class RoleBean implements Serializable {
    private final Logger logger = LoggerFactory.getLogger(RoleBean.class);
    
    @Inject private RoleJpaController roleController;
    @Inject private PageJpaController pageController;
    @Inject private Conversation conversation;
    private Role[] selectedRoles;
    private Role role;
    private List<Role> roleList;
    
    private DualListModel<Page> pageModels;
    
    @PostConstruct
    public void init(){
        roleList = roleController.find();
    }

    public List<Role> getRoleList() {
        return roleList;
    }
    
    public Role.RoleCode[] getRoleCodes() {
        return Role.RoleCode.values();
    }

    public Role getRole(String name){
        return this.roleController.findByName(name);
    }
    
    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public Role[] getSelectedRoles() {
        return selectedRoles;
    }

    public void setSelectedRoles(Role[] selectedRoles) {
        this.selectedRoles = selectedRoles;
    }

    public DualListModel<Page> getPageModels() {
        return pageModels;
    }

    public void setPageModels(DualListModel<Page> pageModels) {
        this.pageModels = pageModels;
    }
    
    public Conversation getConversation() {
        return conversation;
    }
    
    public void preNewAction() {
        role = new Role();
        this.initPageModels();
        
        if (conversation.isTransient()) {
            conversation.begin();
        }
    }
    
    public String preViewAction() {
        String outcome = "";
        FacesContext context = FacesContext.getCurrentInstance();
        
        try {
            if (conversation.isTransient()) {
                conversation.begin();
            }
            
            if(this.role != null)
                outcome = "view?faces-redirect=true";
            else if (this.selectedRoles == null || this.selectedRoles.length == 0) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn một role", ""));
            } else if (this.selectedRoles.length > 1) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn chỉ một role", ""));
            } else {
                this.role = this.selectedRoles[0];
                outcome = "view?faces-redirect=true";
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
        return outcome;
    }
    
    public String preEditAction() {
        String outcome = null;
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            if (conversation.isTransient()) {
                conversation.begin();
            }
            
            if(this.role != null){
                this.initPageModels();
                outcome = "edit?faces-redirect=true";
            } else if (this.selectedRoles == null || this.selectedRoles.length == 0) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn một role", ""));
            } else if (this.selectedRoles.length > 1) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn chỉ một role", ""));
            } else {
                this.role = this.selectedRoles[0];
                this.initPageModels();
                outcome = "edit?faces-redirect=true";
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));

        }
        return outcome;
    }
    
    private void initPageModels() {
        List<Page> pageList = this.pageController.find();
        if(this.role == null || this.role.getPages() == null) {
            pageModels = new DualListModel<Page>(pageList, new ArrayList<Page>());
        } else {
            for (Page page : this.role.getPages()) {
                pageList.remove(page);
            }
            if(pageModels == null)
                pageModels = new DualListModel<Page>(pageList, new ArrayList<Page>());
            this.pageModels.setSource(pageList);
            this.pageModels.setTarget(this.role.getPages());
        }
    }
    
    public void preDeleteAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            if (conversation.isTransient()) {
                conversation.begin();
            }
            if ((this.role == null) && (this.selectedRoles == null || this.selectedRoles.length == 0)) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn role", ""));
            }
        } catch (Exception e) {
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
    }
    
    public String saveAction() {
        try {
            this.roleController.create(role);
            return "view?faces-redirect=true";
        } catch (Exception ex) {
            this.logger.error(ex.getMessage(), ex);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
            return null;
        }
    }
    
    public String updateAction() {
        try {
            this.roleController.edit(role);
            return "view?faces-redirect=true";
        } catch (Exception ex) {
            this.logger.error(ex.getMessage(), ex);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
            return null;
        }
    }

    public String cancelAction() {
        conversation.end();
        return "list?faces-redirect=true";
    }
    
    public void deleteAction() {
        try {
            if(this.role != null)
                this.roleController.destroy(this.role.getId());
            else
                for(Role selectedRole : selectedRoles)                
                    this.roleController.destroy(selectedRole.getId());
            if(!conversation.isTransient())
                conversation.end();
            FacesContext.getCurrentInstance().getExternalContext().redirect("list.vfs");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
    }
}
